package net.sourceforge.jweb.json;

public abstract class JSONElement {

	/**
	 * this object name
	 */
	private String name;
	private String quotoString = "'";
	private Boolean quotoName = null;
	private boolean quotoValue = true;
	private boolean strict = true;

	public final String getName() {
		return name;
	}

	public final void setName(String name) {
		this.name = name;
	}

	public final String getQuotoString() {
		return quotoString;
	}

	public final void setQuotoString(String quotoString) {
		this.quotoString = quotoString;
	}

	public final boolean isQuotoName() {
		return quotoName == null || quotoName;
	}

	public final boolean quotoNameSet() {
		return quotoName != null;
	}

	public final void setQuotoName(boolean quotoName) {
		this.quotoName = quotoName;
	}

	public final boolean isQuotoValue() {
		return quotoValue;
	}

	public final void setQuotoValue(boolean quotoValue) {
		this.quotoValue = quotoValue;
	}
	/**
	 * if set strict mode, then json value will escape char such as ' ' as \\t ...
	 * @return
	 */
	public final boolean isStrict() {
		return strict;
	}
	/**
	 * if set strict mode, then json value will escape char such as ' ' as \\t ...
	 * @return
	 */
	public final void setStrict(boolean strict) {
		this.strict = strict;
	}

	/**
	 * Produce a string in double quotes with backslash sequences in all the right
	 * places. A backslash will be inserted within </, allowing JSON text to be
	 * delivered in HTML. In JSON text, a string cannot contain a control character
	 * or an unescaped quote or backslash.
	 * 
	 * @param string
	 *            A String
	 * @return A String correctly formatted for insertion in a JSON text.
	 */
	protected static String quote(String string, String quoto, boolean strict) {
		if (string == null || string.length() == 0) {
			return "\"\"";
		}
		char b;
		char c = 0;
		int i;
		int len = string.length();
		StringBuilder sb = new StringBuilder(len + 4);
		String t;

		sb.append(quoto);
		
		if(strict) {
			for (i = 0; i < len; i += 1) {
				b = c;
				c = string.charAt(i);
				switch (c) {
				case '\\':
				case '"':
					sb.append('\\');
					sb.append(c);
					break;
				case '/':
					if (b == '<') {
						sb.append('\\');
					}
					sb.append(c);
					break;
				case '\b':
					sb.append("\\b");
					break;
				case '\t':
					sb.append("\\t");
					break;
				case '\n':
					sb.append("\\n");
					break;
				case '\f':
					sb.append("\\f");
					break;
				case '\r':
					sb.append("\\r");
					break;
				default:
					if (c < ' ') {
						t = "000" + Integer.toHexString(c);
						sb.append("\\u" + t.substring(t.length() - 4));
					} else {
						sb.append(c);
					}
				}
			}
		}
		else {
			sb.append(string);
		}
		sb.append(quoto);
		return sb.toString();
	}
}
